package com.fintech.pangu.security.authentication.config;

import com.fintech.pangu.security.authentication.filter.ApiLoginAuthenticationFilter;
import com.fintech.pangu.security.config.PanGuHttpSecurityConfigurer;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.util.ArrayList;
import java.util.List;

/**
 * Api Login/Logout安全配置
 */
@Setter
public class ApiLoginPanGuHttpSecurityConfig extends PanGuHttpSecurityConfigurer {

    /**
     * Api Login 登录成功处理器
     */
    private AuthenticationSuccessHandler apiLoginAuthenticationSuccessHandler;

    /**
     * Api Login 登录失败处理器
     */
    private AuthenticationFailureHandler apiLoginAuthenticationFailureHandler;

    /**
     * Api Logout 登出处理器
     */
    private LogoutHandler apiLogoutHandler;

    /**
     * Api Logout 登出成功处理器
     */
    private LogoutSuccessHandler apiLogoutSuccessHandler;


    @Override
    public void configure(HttpSecurity http) throws Exception {
        // Api Login Filter
        ApiLoginAuthenticationFilter apiLoginAuthenticationFilter = new ApiLoginAuthenticationFilter();
        apiLoginAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); //使用统一的认证管理器
        apiLoginAuthenticationFilter.setAuthenticationSuccessHandler(apiLoginAuthenticationSuccessHandler); //成功处理器
        apiLoginAuthenticationFilter.setAuthenticationFailureHandler(apiLoginAuthenticationFailureHandler); //失败处理器

        http.addFilterBefore(apiLoginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        // Api Logout Filter
        List<LogoutHandler> logoutHandlers = new ArrayList<>();
        logoutHandlers.add(apiLogoutHandler); // API登出处理器
        LogoutHandler[] handlers = logoutHandlers.toArray(new LogoutHandler[logoutHandlers.size()]);

        // 创建apiLogoutFilter，设置LogoutHandler 和 LogoutSuccessHandler
        LogoutFilter apiLogoutFilter = new LogoutFilter(apiLogoutSuccessHandler, handlers);
        apiLogoutFilter.setLogoutRequestMatcher(new AntPathRequestMatcher("/api/logout", "POST"));

        http.addFilterBefore(apiLogoutFilter, LogoutFilter.class);
    }

}
